package com.blog.interceptor.frontend;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FrontendInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        System.out.println("frontend interceptor invoke");
//        System.out.println(response);
//        System.out.println(request);
        String[] allowUrls = new String[]{"/register", "/login", "frontend/product/index"};
        String url = request.getRequestURL().toString();
        for (String strUrl : allowUrls) {
            if (url.contains(strUrl)) {
//                System.out.println(strUrl);
                return true;
            }
        }
        HttpSession session = request.getSession();
//        System.out.println(session.getAttribute("isLogin"));
        if (session.getAttribute("isLogin") == null) {
            response.sendRedirect(request.getContextPath() + "/frontend/user/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
